package com.taobao.fanli.controller;

import com.taobao.api.ApiException;
import com.taobao.fanli.common.RestResponse;
import com.taobao.fanli.dao.model.Taobao;
import com.taobao.fanli.service.TaobaoFanliService;
import com.taobao.fanli.utils.EmojiFilter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:xiaolei
 * @date:2018/4/5
 */
@RestController
@RequestMapping(value = "/fanli")
@Api(value="淘口令处理接口api",description="淘口令处理接口api")
public class TaobaoFanliController {

    private static final Logger logger = LoggerFactory.getLogger("TaobaoFanliController");

    @Resource
    private TaobaoFanliService taobaoFanliService;

    @RequestMapping(value = "/parseTpwd", method = RequestMethod.POST)
    @ApiOperation(value="解析淘口令", notes="解析淘口令", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "淘口令内容", required = true, dataType = "String", paramType = "query")
    })
    public RestResponse parseTpwd(
            @RequestParam(value = "content") String content
    ) {
        try {
            String newContent = EmojiFilter.filterEmoji(content);
            Map<String, Integer> result = taobaoFanliService.parseTpwd(newContent);
            return new RestResponse(result);
        } catch (ApiException e) {
            logger.error("taobaofanli parseTpwd error:", e);
            return new RestResponse(e.getErrMsg(), Integer.parseInt(e.getErrCode()));
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value="淘口令更新", notes="淘口令更新", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "failed", value = "失败关键字", required = true, dataType = "Integer", paramType = "update"),
            @ApiImplicitParam(name = "newTaobaoPassword", value = "新的淘口令", required = true, dataType = "String", paramType = "update"),
            @ApiImplicitParam(name = "rebateRatio", value = "返利比率", required = true, dataType = "String", paramType = "update"),
            @ApiImplicitParam(name = "rebateMoney", value = "返利金额", required = true, dataType = "String", paramType = "update"),
    })
    public RestResponse update(
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "failed") Integer failed,
            @RequestParam(value = "newTaobaoPassword", required = false) String newTaobaoPassword,
            @RequestParam(value = "rebateRatio", required = false) String rebateRatio,
            @RequestParam(value = "rebateMoney", required = false) String rebateMoney
    ) {
        try {
            //|| StringUtils.isEmpty(rebateRatio)
            if(failed == 0 && (StringUtils.isEmpty(newTaobaoPassword))){
                return new RestResponse("淘口令或返利比率不能为空", 505);
            }
            taobaoFanliService.update(id, newTaobaoPassword, failed, rebateRatio, rebateMoney);
            Map<String, Integer> map = new HashMap<>();
            map.put("state", 1);
            return new RestResponse(map);
        } catch (Exception e) {
            logger.error("taobaofanli update error:", e);
            return new RestResponse("更新出错", 505);
        }
    }

    @RequestMapping(value = "/queryOne", method = RequestMethod.GET)
    @ApiOperation(value="淘口令id查询", notes="淘口令id查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "String", paramType = "query")
    })
    public RestResponse queryOne(
            @RequestParam(value = "id") String id
    ) {
        try {
            if(!isNumeric(id)){
                return new RestResponse("参数类型有误", 505);
            }
            Taobao taobao = taobaoFanliService.queryOne(Integer.valueOf(id));
            if(taobao != null){
                if(taobao.getState() == 4){
                    taobao.setRebateRatio("0");
//                    return new RestResponse("此商品没有返利", 121);
                }
                return new RestResponse(taobao);
            }else{
                return new RestResponse("数据正在处理中，请稍后", 505);
            }

        } catch (Exception e) {
            logger.error("taobaofanli query error:", e);
            return new RestResponse("更新出错", 505);
        }
    }

    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    @RequestMapping(value = "/queryState", method = RequestMethod.GET)
    @ApiOperation(value="淘口令状态查询", notes="淘口令状态查询", httpMethod = "GET")
    public RestResponse queryState() {
        try {
            Taobao taobao = taobaoFanliService.queryState();
            if(taobao != null){
                return new RestResponse(taobao);
            }else{
                return new RestResponse("无数据处理", 505);
            }
        } catch (Exception e) {
            logger.error("taobaofanli query error:", e);
            return new RestResponse("更新出错", 505);
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ApiOperation(value="淘口令id删除", notes="淘口令id删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "Integer", paramType = "query")
    })
    public RestResponse delete(
            @RequestParam(value = "id") Integer id) {
        try {
            taobaoFanliService.delete(id);
            return new RestResponse("删除成功 id:"+id);
        } catch (Exception e) {
            logger.error("taobaofanli query error:", e);
            return new RestResponse("更新出错", 505);
        }
    }

    @RequestMapping(value = "/deleteByCode", method = RequestMethod.GET)
    @ApiOperation(value="淘口令code删除", notes="淘口令code删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "老的淘口令", required = true, dataType = "String", paramType = "query")
    })
    public RestResponse delete(
            @RequestParam(value = "code") String oldTaobaoPassword) {
        try {
            taobaoFanliService.deleteByCode(oldTaobaoPassword);
            return new RestResponse("删除成功 oldTaobaoPassword:"+oldTaobaoPassword);
        } catch (Exception e) {
            logger.error("taobaofanli query error:", e);
            return new RestResponse("更新出错", 505);
        }
    }

}
